<?php

namespace app\api\controller\v2;

use app\api\controller\Common;

define('WXPAY', ROOT_PATH . "wechatpay" . DS);
require ROOT_PATH . 'wechatpay/lib/WxPay.Config.php';

// require ROOT_PATH . 'wechatpay/lib/WxPay.Data.php';

class OrderVip extends Common
{
    public $modelDb;

    public function _initialize()
    {
        parent::_initialize();
        $this->modelDb = model("OrderVip");
    }

    // 创建微信订单时，根据openid，获取微信prepay_id，然后生成一些参数（签名及其他5个字段），最后将生成的一些参数回传给app，并将订单信息入库
    public function create_order()
    {
        if (isset($this->postData['type']) && $this->postData['type'] == 1) {
            $count = model('MemberCoupons')->where('couponsid', 11)->where('isactivate', 1)->count();
            if ($count >= 1000) {
                return $this->app_success([], '可激活数量为0');
            }
            $count = model('MemberCoupons')->where('userid', $this->uinfo['userid'])->where('couponsid', 11)->where('isactivate', 1)->count();
            if ($count) {
                return $this->app_success([], '已有一张已激活的购车券，请勿重复激活！');
            }
        }
        // if (!isset($this->postData['code']) || !$this->postData['code']) {
        // 	return $this->app_error('支付失败');
        // }
        $result = $this->modelDb->save_datas($this->postData, $this->uinfo);
        if ($result === false) {
            return $this->app_error($this->modelDb->getError());
        }
        $payinfo = $this->get_weixin_jsprepay_id($result);
        if ($payinfo === false) {
            return $this->app_error('支付失败');
        }
        if (isset($result['vipendtime'])) {
            $payinfo['vipendtime'] = $result['vipendtime'];
        }
        return $this->app_success($payinfo);
    }

    protected function get_weixin_jsprepay_id($info)
    {
        // 2、根据openid，组装数据，获取prepayid
        require_once WXPAY . "lib/WxPay.Api.php";
        require_once WXPAY . "example/WxPay.NativePay.php";
        require_once WXPAY . 'example/log.php';
        require_once WXPAY . 'lib/WxPay.Data.php';

        // 组装数据
        if ($this->uinfo['openid']) {
            $openid = $this->uinfo['openid'];
            $input = new \WxPayUnifiedOrder();
            $input->SetBody($info['description']);
            $input->SetAttach($info['description']);
            $input->SetOut_trade_no($info['ordersn']);
            $input->SetTotal_fee($info['payprice'] * 100);
            $input->SetGoods_tag($info['description']);
            $input->SetNotify_url(rtrim(APP_URL, "/") . url("v2/pay/weixin_pay"));
            $input->SetTrade_type("JSAPI");
            $input->SetOpenid($openid);
            $wxPayApi = new \WxPayApi();
            $order = $wxPayApi::unifiedOrder($input);
            // 获取到prepay_id，需要返回给app
            $prepay_id = $order['prepay_id'];
            //
            $wxpayinfoData = [
                'ordersn' => $info['ordersn'],
                'prepayid' => $prepay_id,
            ];
            model('WxpayInfo')->save_datas($wxpayinfoData);
            // 3、生成签名及其他5个字段
            $timeStamp = time();
            $wxconfig = new \WxPayConfig();
            $signArr2 = [
                'appId' => $wxconfig::WX_APPID,
                'nonceStr' => $order['nonce_str'],
                'package' => 'prepay_id=' . $prepay_id,
                'signType' => 'MD5',
                'timeStamp' => $timeStamp,
            ];
            $wxdatabase = new \WxPayDataBase();
            $newSign = $wxdatabase->MakeSign2($signArr2);
            $returnData = [
                'timeStamp' => $timeStamp,
                'nonceStr' => $order['nonce_str'],
                'package' => 'prepay_id=' . $prepay_id,
                'signType' => 'MD5',
                'paySign' => $newSign,
            ];
            return $returnData;
        } else {
            // 获取openid
            // $wxutils = new WXUtils();
            // $openid = $wxutils->get_wechat_openid($this->postData['code']);
            // $openid = $this->get_wechat_openid($this->postData['code']);
            return $this->app_error('openid不能为空');
        }
    }

    // 缴费列表
    public function orderlist()
    {
        $data = model('OrderVip')->where('userid', $this->uinfo['userid'])->where('status', 1)->field('ordersn, price, paytype, status, description, paytime, dateline')->select();
        // trace()
        return $this->app_success($data);
    }

    public function chongzhi()
    {
        $totalprice = $this->postData['totalprice'];
        if (empty($totalprice)) {
            return $this->app_error('请输入金额！');
        }
        $this->postData['userid'] = $this->uinfo['id'];
        // $result = $this->validate($this->postData, 'Member.check_price');
        // if ($result !== true) {
        //     return $this->app_error($result);
        // }
        list($bool, $data) = $this->modelDb->save_datas($this->postData);
        if ($bool !== true) {
            return $this->app_error($bool);
        } else {
            return $this->app_success($data);
        }
    }

    public function tixian()
    {
        if ($this->postData['totalprice'] < config('DEPOSIT_MINPRICE')) {
            return $this->app_error('提现金额不能低于' . config('DEPOSIT_MINPRICE') . '元');
        }
        if ($this->postData['totalprice'] > $this->uinfo['amount']) {
            return $this->app_error('余额不足');
        }
        $this->postData['userid'] = $this->uinfo['id'];
        $this->postData['province'] = model("City")->where('id', $this->postData['province'])->value('title');

        $result = $this->validate($this->postData, 'Member.check_paytype');
        if ($result !== true) {
            return $this->app_error($result);
        }
        $id = model("OrderDeposit")->save_datas($this->postData);
        if (!$id) {
            return $this->app_error(model("OrderDeposit")->getError());
        }
        $id = model("MemberCard")->save_datas($this->postData);
        return $this->app_success();
    }

    /**
     *手动续费荣耀会员
     */
    public function viprenew()
    {
        $userid = $this->postData['userid'];
        $userinfo = model('AdminUser')->where('userid', $userid)->find();
//        return $this->app_success($userinfo);
        $vip = $userinfo['vip'];
        $vipendtime = $userinfo['vipendtime'];
        if ($vip == 0) { // 当前是非会员状态
            if ($vipendtime) { // 说明之前是会员，目前是过期状态
                $this->modelDb->save_order_viprenew($userid);
                $endtime = strtotime(date('Y-m-d', strtotime('+1 year')) . ' 23:59:59');
                model('AdminUser')->where('userid', $userid)->update(['vipendtime' => $endtime, 'vip' => 1, 'viprenew' => $userinfo['viprenew'] + 1]);
                return $this->app_success([], '续费成功');
            } else {
                return $this->app_error('该用户还不是荣耀会员');
            }
        } else if ($vip == 1) {
            return $this->app_error('该用户已经是荣耀会员了');
        }
    }
}
